const app = getApp()
const { envList } = require('../../envList')
Page({
  data: {
    curDate: Date,
    formatDate: '',
    dateTypes: ['工作日', '休息日', '节假日'],
    typeIndex: 0,
    jbHour: 0,
    qjHour: 0
  },

  onLoad: function (options) {
    this.data.curDate = new Date(Number(options.time));
    this.setData({
      formatDate: this.data.curDate.getFullYear() + '-' + (this.data.curDate.getMonth() + 1) + '-' + this.data.curDate.getDate(),
      typeIndex: Number(options.dateType),
      jbHour: isNaN(parseFloat(options.jbHour)) ? 0 : parseFloat(options.jbHour),
      qjHour: isNaN(parseFloat(options.qjHour)) ? 0 : parseFloat(options.qjHour)
    })

  },

  bindRegionChange(e) {
    this.setData({
      typeIndex: Number(e.detail.value)
    })
  },

  async saveData() {
    const Collection = wx.cloud.database({
      env: envList[1].envId
    }).collection('WorkRecord');
    await Collection.where({
      _openid: app.globalData.openId,
      Date: this.data.curDate
    }).get().then(async res => {
      if (res.data.length > 0) {
        if (this.data.jbHour > 0 || this.data.qjHour > 0) {
          await Collection.doc(res.data[0]._id).update({
            data: {
              JbHour: this.data.jbHour,
              QjHour: this.data.qjHour,
              DayType: this.data.typeIndex
            }
          })
        } else {
          await Collection.doc(res.data[0]._id).remove()
        }
      } else {
        if (this.data.jbHour > 0 || this.data.qjHour > 0) {
          await Collection.add({
            data: {
              Date: this.data.curDate,
              DayType: this.data.typeIndex,
              JbHour: this.data.jbHour,
              QjHour: this.data.qjHour
            }
          })
        }
      }
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1000
      }).then(() => {
        setTimeout(function () {
          wx.navigateBack();
        }, 1100)
      })
    })
  },

  inputFocus: function (e) {
    if (e.target.id == 'jbh') {
      this.setData({
        'jbh_focus': true
      });
    } else if (e.target.id == 'qjh') {
      this.setData({
        'qjh_focus': true
      });
    }
  },
  inputBlur: function (e) {
    if (e.target.id == 'jbh') {
      this.setData({
        'jbh_focus': false,
        jbHour: isNaN(parseFloat(e.detail.value)) ? 0 : parseFloat(e.detail.value)
      });
    } else if (e.target.id == 'qjh') {
      this.setData({
        'qjh_focus': false,
        qjHour: isNaN(parseFloat(e.detail.value)) ? 0 : parseFloat(e.detail.value)
      });
    }
  }
})